/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package komunikaty;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;


/**
 *
 * @author pd
 */
public class Statistics implements Serializable{

    private ArrayList<Card.Vote> votes;
    private int liczbaMogacychGlosowac;
    private List<HashMap<BigInteger,Integer>> wyniki;
    private int liczbaGlosow = 0;

    public Statistics(Card.Vote[] votes, int liczba) {
        Map<BigInteger, Card.Vote> _votes;
        _votes = new HashMap<BigInteger, Card.Vote>();
        liczbaMogacychGlosowac=liczba;
        //wywalenie duplikatow
        for (Card.Vote v : votes) {
            _votes.put(v.serial, v);
        }
        this.votes = new ArrayList<Card.Vote>();
        this.votes.addAll(_votes.values());
        gen();
    }

    private void gen() {
        HashMap<BigInteger, Integer> w = new HashMap<BigInteger, Integer>();

        for (Card.Vote v : votes) {
            if (w.containsKey(v.candidate)) {
               w.put(v.candidate, new Integer(w.get(v.candidate).intValue() + 1));
            } else {
                w.put(v.candidate, new Integer(1));
            }
            liczbaGlosow++;
                  
        }
    
        List<HashMap<BigInteger,Integer>> list = new LinkedList<HashMap<BigInteger,Integer>>();
        Iterator<Entry<BigInteger,Integer>> it=w.entrySet().iterator();
        while (it.hasNext())
        {
          Entry<BigInteger,Integer> en=  it.next();
          HashMap<BigInteger,Integer> hm=new HashMap<BigInteger,Integer>();
          hm.put(en.getKey(),en.getValue());
          list.add(hm);
        }       
        
      Collections.sort( list, new Comparator<HashMap<BigInteger,Integer>>() {
      public int compare( HashMap<BigInteger,Integer> entry1, HashMap<BigInteger,Integer> entry2 ) {
        return entry2.entrySet().iterator().next().getValue()
                .compareTo( entry1.entrySet().iterator().next().getValue());
      }
    });
    wyniki=list;
     //  wyniki.addAll(w.entrySet());
    }

    public List<HashMap<BigInteger,Integer>> getWynikiDlaKandydatow() {
        return wyniki;
    }

    public ArrayList<Card.Vote> getVotes() {
        return votes;
    }

    public int liczbaGlosujacych() {
        return liczbaGlosow;
    }

    public int liczbaMogacychGlosowac() {
        return liczbaMogacychGlosowac;
    }

    public double wynikProcentowyDlaKandydata(Entry<BigInteger, Integer> k){ 
        return (k.getValue().intValue()/(double)liczbaGlosow)*100.0;
    }
}
